package com.xq.shop.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xq.shop.config.Redis;
import com.xq.shop.dao.domain.entity.ExchangeRate;
import com.xq.shop.service.IExchangeRateService;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

/**
 * @author gaoxiaojin
 */
@Component
@Slf4j
public class MyJob {

    @Resource
    private IExchangeRateService exchangeRateService;
    @Resource
    private Redis redis;


    @Scheduled(cron = "0 0/30 * ? * *")
    public void exchangeRate() {
        log.info("定时任务开始执行");
        LambdaQueryWrapper<ExchangeRate> wrapper = new LambdaQueryWrapper<>();
        Calendar calendar = Calendar.getInstance();
        // 将时分秒设置为0，即当天的凌晨时间（0点）
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        wrapper.gt(ExchangeRate::getCreateTime, calendar.getTime());
        ExchangeRate exchangeRate = exchangeRateService.getOne(wrapper);
        boolean isSet = false;
        if (Objects.isNull(exchangeRate)) {
            isSet = true;
        } else {
            if (Objects.isNull(exchangeRate.getOldExchangeRate())) {
                isSet = true;
            }
        }
        if (isSet) {
            BigDecimal rate = getRate();
            rate = rate.add(BigDecimal.valueOf(0.5));
            if (Objects.isNull(exchangeRate)) {
                exchangeRate = new ExchangeRate();
                exchangeRate.setExchangeRate(rate);
                exchangeRateService.save(exchangeRate);
                redis.remove("exchangeRate");
            } else {
                if (!exchangeRate.getExchangeRate().equals(rate)) {
                    exchangeRate.setExchangeRate(rate);
                    exchangeRateService.updateById(exchangeRate);
                    redis.remove("exchangeRate");
                }
            }
        }
    }

//    @Scheduled(cron = "0 0 23 * * ?")
//    public void crawling() {
//        log.info("定时任务开始执行>>执行自动爬取");
//        try {
//            // 执行命令
//            Runtime.getRuntime().exec("python C:\\getALiData\\GoodsNetworkByLeTianFixedTime.py");
//            log.info("定时任务开始执行>>执行自动爬取成功》》》");
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error(e.getMessage());
//        }
//    }

    public BigDecimal getRate() {

        String url = "https://www.bk.mufg.jp/ippan/rate/real.html";
        // 爬取网页获取第一个参数集
        //System.setProperty("webdriver.chrome.driver", "/Users/gaoxiaojin/environment/chromedriver");
        System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
        // 初始化 WebDriver
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless");
        options.addArguments("--start-maximized");
        WebDriver driver = new ChromeDriver(options);
        driver.get(url);
        WebElement tbody = driver.findElement(By.tagName("tbody"));
        List<WebElement> elements = tbody.findElements(By.tagName("tr"));
        String s = "";
        for (WebElement e : elements) {
            List<WebElement> element = e.findElements(By.className("m-table-legacy_bg2"));
            if (element.get(1).getText().contains("CNY")) {
                WebElement rate = e.findElement(By.id("G069TTSZ"));
                s = rate.getText();
                driver.quit();
                break;
            }
        }
        return BigDecimal.valueOf(Double.parseDouble(s));
    }

}
